package aplicacion;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.io.BufferedOutputStream;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableModel;

import dominio.Cliente;
import dominio.Direccion;
import extras.AppendingObjectOutputStream;
import net.miginfocom.swing.MigLayout;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MenuCliente {
	private JPanel panelPrincipal;
	private JPanel panelIzquierda;
	private JPanel panelCentro;
	private JPanel panelArriba;
	private JTextField txtTxtbuscar;
	private JTable table;

	MenuCliente (){
		panelPrincipal = new JPanel();
		panelPrincipal.setLayout( new BorderLayout() );
		cargarPanelArriba();
		cargarPanelIzquierda();
		cargarPanelMedio();
	}
	
	public void cargarPanelArriba(){
		panelArriba = new JPanel();
		panelArriba.setLayout(new MigLayout("", "[grow][]", "[]"));
		
		txtTxtbuscar = new JTextField();
		txtTxtbuscar.setPreferredSize(new Dimension(4, 25));
		panelArriba.add(txtTxtbuscar, "cell 0 0,growx");
		txtTxtbuscar.setColumns(10);
		{
			JButton btbBuscar = new JButton("Buscar");
			btbBuscar.setIcon(new ImageIcon(MenuCliente.class.getResource("/aplicacion/imagenes/buscar.png")));
			panelArriba.add(btbBuscar, "cell 1 0,alignx right");
			
		}
		panelPrincipal.add(panelArriba, BorderLayout.NORTH);
	}
	
	public void cargarPanelIzquierda(){
		panelIzquierda = new JPanel();
		panelIzquierda.setLayout(new MigLayout());
		{
			JButton btbAgregar = new JButton("Agregar");
			btbAgregar.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent arg0) {
					new MenuAgregarCliente().setVisible(true); 
					cargarPanelMedio();
				}
			});
			btbAgregar.setIconTextGap(12);
			btbAgregar.setHorizontalAlignment(SwingConstants.LEFT);
			btbAgregar.setHorizontalTextPosition(SwingConstants.LEFT);
			btbAgregar.setIcon(new ImageIcon(MenuCliente.class.getResource("/aplicacion/imagenes/agregar_cliente.png")));
			panelIzquierda.add(btbAgregar, "cell 0 0,growx,aligny top");
			
			JButton btbModificar = new JButton("Modificar");
			btbModificar.setHorizontalAlignment(SwingConstants.LEFT);
			btbModificar.setHorizontalTextPosition(SwingConstants.LEFT);
			btbModificar.setIcon(new ImageIcon(MenuCliente.class.getResource("/aplicacion/imagenes/modificar_cliente.png")));
			panelIzquierda.add(btbModificar, "cell 0 1,alignx left,growy");

			JButton btbEliminar = new JButton("Eliminar");
			btbEliminar.setIconTextGap(12);
			btbEliminar.setHorizontalAlignment(SwingConstants.LEFT);
			btbEliminar.setHorizontalTextPosition(SwingConstants.LEFT);
			btbEliminar.setIcon(new ImageIcon(MenuCliente.class.getResource("/aplicacion/imagenes/eliminar_cliente.png")));
			panelIzquierda.add(btbEliminar, "cell 0 2,grow");
		}	
		panelPrincipal.add(panelIzquierda, BorderLayout.WEST);
	}
	
	public void cargarPanelMedio(){
		panelCentro = new JPanel();
		panelCentro.setLayout( new GridLayout() );
		panelPrincipal.add(panelCentro, BorderLayout.CENTER);
		String[] columnNames = {"ID Cliente","Nombre","Apellido",
				"Usuario", "Direccion",
				"Telefono","Documento", "Email",};
		table = new JTable(new DefaultTableModel(null, columnNames));
		try {
			agregarFila();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		JScrollPane scrollPane = new JScrollPane(table);
		panelCentro.add(scrollPane);		
	}
	
	void agregarFila() throws ClassNotFoundException, IOException{
		File file = new File("bin/aplicacion/archivos/clientes.txt");
		if (file.exists()){
			DefaultTableModel defaultModel = (DefaultTableModel) table.getModel();  
			ObjectInputStream ois = null;
			try{
				ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
				while(true){
					Cliente c = (Cliente) ois.readObject();
					defaultModel.addRow(new Object[]{ c.getIdCliente().toString(),
													c.getNombre(),
													c.getApellido(),
													c.getNombreUsuario(),
													//c.getPassword(),
													c.getDireccion(),
													c.getTelefono(),
													c.getDni(),
													c.getEmail(),});
					}
			}catch(EOFException e){
				
			}finally{
				if(ois != null){
					ois.close();
				}
			}
			table = new JTable(defaultModel);
		}   
	}

	public JPanel getPanel() {
		return panelPrincipal;
	}

	public void setPanel(JPanel panel) {
		this.panelPrincipal = panel;
	}

}

@SuppressWarnings("serial")
class MenuAgregarCliente extends JDialog {
	private JTextField txtIdCliente;
	private JTextField txtNombre;
	private JTextField txtApellido;
	private JTextField txtUsuario;
	private JTextField txtPassword;	
	private JTextField txtTelefono;
	private JTextField txtDocumento;
	private JTextField txtMail;
	
	private JTextField txtCalle;
	private JTextField txtNumeroCalle;
	private JTextField txtCodPostal;
	private JTextField txtCiudad;
	private JTextField txtProvincia;
	private JTextField txtPais;
	
	MenuAgregarCliente(){
		setSize(500, 480);
		setLocationRelativeTo(null);
		setModal (true);
		setAlwaysOnTop (true);
		setModalityType (ModalityType.APPLICATION_MODAL);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		getContentPane().setLayout(new MigLayout());
		
		JLabel lblIdCliente = new JLabel("IDCliente:");
		txtIdCliente = new JTextField();
		txtIdCliente.setMinimumSize(new Dimension(200,25));
		add(lblIdCliente, "cell 0 0");
		add(txtIdCliente, "cell 1 0, growx");
		
		JLabel lblNombre = new JLabel("Nombre:");
		txtNombre = new JTextField();
		txtNombre.setMinimumSize(new Dimension(200,25));
		add(lblNombre, "cell 0 1");
		add(txtNombre, "cell 1 1, growx");
		
		JLabel lblApellido = new JLabel("Apellido:");
		txtApellido = new JTextField();
		txtApellido.setMinimumSize(new Dimension(200,25));
		add(lblApellido, "cell 0 2");
		add(txtApellido, "cell 1 2, growx");
		
		JLabel lblUsuario = new JLabel("Usuario:");
		txtUsuario = new JTextField();
		txtUsuario.setMinimumSize(new Dimension(200,25));
		add(lblUsuario, "cell 0 3");
		add(txtUsuario, "cell 1 3, growx");
		
		JLabel lblPassword = new JLabel("Password:");
		txtPassword = new JTextField();
		txtPassword.setMinimumSize(new Dimension(200,25));
		add(lblPassword, "cell 0 4");
		add(txtPassword, "cell 1 4, growx");
		
		JLabel lblTelefono = new JLabel("Telefono:");
		txtTelefono = new JTextField();
		txtTelefono.setMinimumSize(new Dimension(200,25));
		add(lblTelefono, "cell 0 5");
		add(txtTelefono, "cell 1 5, growx");
		
		JLabel lblDocumento = new JLabel("Documento:");
		txtDocumento = new JTextField();
		txtDocumento.setMinimumSize(new Dimension(200,25));
		add(lblDocumento, "cell 0 6");
		add(txtDocumento, "cell 1 6, growx");
		
		JLabel lblMail = new JLabel("Mail:");
		txtMail = new JTextField();
		txtMail.setMinimumSize(new Dimension(200,25));
		add(lblMail, "cell 0 7");
		add(txtMail, "cell 1 7, growx");
		
		JLabel lblCalle = new JLabel("Calle:");
		txtCalle = new JTextField();
		txtCalle.setMinimumSize(new Dimension(200,25));
		add(lblCalle, "cell 0 8");
		add(txtCalle, "cell 1 8, growx");
		
		JLabel lblNumeroCalle = new JLabel("N°:");
		txtNumeroCalle = new JTextField();
		txtNumeroCalle.setMinimumSize(new Dimension(50,25));
		add(lblNumeroCalle, "cell 2 8");
		add(txtNumeroCalle, "cell 3 8, growx");
		
		JLabel lblCodPostal = new JLabel("CP:");
		txtCodPostal = new JTextField();
		txtCodPostal.setMinimumSize(new Dimension(50,25));
		add(lblCodPostal, "cell 4 8");
		add(txtCodPostal, "cell 5 8, growx");
		
		JLabel lblCiudad = new JLabel("Ciudad:");
		txtCiudad = new JTextField();
		txtCiudad.setMinimumSize(new Dimension(200,25));
		add(lblCiudad, "cell 0 9");
		add(txtCiudad, "cell 1 9, growx");
		
		JLabel lblPronvicia = new JLabel("Provincia:");
		txtProvincia = new JTextField();
		txtProvincia.setMinimumSize(new Dimension(200,25));
		add(lblPronvicia, "cell 0 10");
		add(txtProvincia, "cell 1 10, growx");
		
		JLabel lblPais = new JLabel("Pais:");
		txtPais = new JTextField();
		txtPais.setMinimumSize(new Dimension(200,25));
		add(lblPais, "cell 0 11");
		add(txtPais, "cell 1 11, growx");
		
		JButton btbAgregar = new JButton("OK");
		btbAgregar.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				ObjectOutputStream oos = null;	
				File file = new File("bin/aplicacion/archivos/clientes.txt");
				try{
					if (file.exists()) {
						oos = new AppendingObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file,true)));
					} else {
						oos = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file,true)));
					}
					Cliente cliente = new Cliente();
					cliente.setIdCliente(new Integer(txtIdCliente.getText()));
					cliente.setNombre(txtNombre.getText());
					cliente.setApellido(txtApellido.getText());
					cliente.setNombreUsuario(txtUsuario.getText());
					cliente.setPassword(txtPassword.getText());
					cliente.setTelefono(txtTelefono.getText());
					cliente.setDni(new Integer(txtDocumento.getText()));
					cliente.setEmail(txtMail.getText());
					
					Direccion direccion = new Direccion();
					direccion.setCalle(txtCalle.getText());
					direccion.setNumero(new Integer(txtNumeroCalle.getText()));
					direccion.setCodPostal(new Integer(txtCodPostal.getText()));
					direccion.setCiudad(txtCiudad.getText());
					direccion.setProvincia(txtProvincia.getText());
					direccion.setPais(txtPais.getText());				
					cliente.setDireccion(direccion);
					
					oos.writeObject(cliente);				
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					if(oos != null){
						try {
							oos.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				} 
			}
		});
		add(btbAgregar, "cell 1 12,growx,aligny top");
	}
}

